package com.jrx.anytxn.param.job.cutover.step;

import com.jrx.anytxn.caffeine.service.ICaffeineMsgPublisher;
import com.jrx.anytxn.common.constant.CommonContants;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.config.CutoverConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.base.BtBatchStatusMapper;
import com.jrx.anytxn.param.mapper.ext.ExtPrOrganizationTableMapper;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 日切清空业务日期缓存设置
 *
 * @author : zhenghaopu
 * 2019/12/6
 */
@Service
public class CutoverListener implements JobExecutionListener {

    private static final Logger logger = LoggerFactory.getLogger(CutoverListener.class);

    @Autowired
    ICaffeineMsgPublisher caffeineMsgPublisher;

    @Resource
    private BtBatchStatusMapper btBatchStatusMapper;

    @Autowired
    private ISegmentService segmentService;

    @Resource
    private ExtPrOrganizationTableMapper extPrOrganizationTableMapper;
    @Autowired
    private HashOperations<String, String, Object> redisHash;
    @Autowired
    private CutoverConfig cutoverConfig;

    @Override
    public void beforeJob(JobExecution jobExecution) {

    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        try {
            caffeineMsgPublisher.sendClearAllMsg();//清除机构缓存
        } catch (Exception e) {
            logger.error("清除机构缓存异常:", e);
        }
        List<String> configBatchTaskIdList = cutoverConfig.getBatchTaskIdList();
        configBatchTaskIdList.forEach(this::cleanRedis);
        record();//记录日终批次信息
    }

    /**
     * 记录日终批次到批次状态信息表
     */
    private void record() {
        PrOrganizationTable org =
                extPrOrganizationTableMapper.selectByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
        BtBatchStatus btBatchStatus = new BtBatchStatus();
        try {
            btBatchStatus.setId(segmentService.getId(Constant.BT_BATCH_STATUS_ID));//id
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
        }
        btBatchStatus.setBatchStatus(Constant.BATCH_SATTUS_2);//状态 2 完成
        btBatchStatus.setBusinessDate(org.getNextProcessingDate());//当前业务日期
        btBatchStatus.setJobName(Constant.CUTOVER_START);//批处理名称
        btBatchStatus.setTenantId(org.getTenantId());//租户id
        btBatchStatus.setUpdateBy(Constant.DEFAULT_USER);
        btBatchStatus.setRecordVersionNumber(Constant.VERSION_NUMBER);//初始版本号
        btBatchStatusMapper.insertSelective(btBatchStatus);
    }

    /**
     * 清除redis数据
     */
    private void cleanRedis(String batchTaskId) {
        // 获取所有key
        String redisKey = String.format(CommonContants.PRODUCT_SUMMARY_REDIS_KEY,batchTaskId);
        Set<String> keys = redisHash.keys(redisKey);
        if(CollectionUtils.isEmpty(keys)){
            return;
        }
        // 迭代
        Iterator<String> it1 = keys.iterator();
        while (it1.hasNext()) {
            // 循环删除
            redisHash.delete(redisKey,it1.next());
        }
    }
}
